package com.rico.smart.device;

import com.rico.smart.message.IMessage;
import com.rico.smart.message.MessageType;
import com.rico.smart.message.MsgMessage;
import com.rico.smart.message.UserLoginMessage;
import com.rico.smart.socket.MessageHandler;
import com.rico.smart.socket.ServerConnectionManager;
import com.rico.smart.socket.SocketClient;
import com.rico.smart.socket.SocketConnection;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Device{
    private static String TAG="Device";

    private DeviceInfo deviceInfo;

    private SocketClient localSocketClient =null;


    private String qrCode;

    private List<MessageHandler> messageHandlerList=new ArrayList<MessageHandler>();

    public Device(){   }

    public Device(DeviceInfo deviceInfo){
        this.deviceInfo=deviceInfo;
    }

    public String getSessionId() {
       return this.deviceInfo.getSessionId();
    }

    public void setSessionId(String sessionId) {
       deviceInfo.setSessionId(sessionId);
    }

    public DeviceInfo getDeviceInfo() {
        return deviceInfo;
    }

    public void setDeviceInfo(DeviceInfo deviceInfo) {
        this.deviceInfo = deviceInfo;
    }


    public void addMessageHandler(MessageHandler messageHandler){
        this.messageHandlerList.add(messageHandler);
    }

    public synchronized IMessage send(IMessage message) throws IOException {
       return ServerConnectionManager.getInstance().sendMessageAndWaitResponse(message);
    }

    public synchronized IMessage send(IMessage message,int waitTime) throws IOException {
        return ServerConnectionManager.getInstance().sendMessageAndWaitResponse(message,waitTime);
    }

    public MsgMessage login() throws IOException {
        UserLoginMessage loginMessage =new UserLoginMessage();
        loginMessage.setReceiver(deviceInfo.getDeviceId());
        loginMessage.setLoginName("");
        loginMessage.setClientType(0);
        loginMessage.setLoginPassword(deviceInfo.getPassword());
        return (MsgMessage)ServerConnectionManager.getInstance().sendMessageAndWaitResponse(loginMessage);
    }

    public boolean isOnline(){
        if(this.deviceInfo.sessionId!=null){
            return true;
        }
        return false;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Device device = (Device) o;

        return deviceInfo != null ? deviceInfo.equals(device.deviceInfo) : device.deviceInfo == null;
    }

    @Override
    public int hashCode() {
        return deviceInfo != null ? deviceInfo.hashCode() : 0;
    }
}
